package com.example.lotterysystem.controller;


import com.example.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.example.lotterysystem.common.exception.ControllerException;
import com.example.lotterysystem.common.pojo.CommonResult;
import com.example.lotterysystem.common.utils.JacksonUtils;
import com.example.lotterysystem.controller.param.CreateActivityParam;
import com.example.lotterysystem.controller.param.PageListParam;
import com.example.lotterysystem.controller.result.CreateActivityResult;
import com.example.lotterysystem.controller.result.FindActivityListResult;
import com.example.lotterysystem.controller.result.FindPrizeListResult;
import com.example.lotterysystem.controller.result.GetActivityDetailResult;
import com.example.lotterysystem.service.ActivityService;
import com.example.lotterysystem.service.dto.ActivityDTO;
import com.example.lotterysystem.service.dto.ActivityDetailDTO;
import com.example.lotterysystem.service.dto.CreateActivityDTO;
import com.example.lotterysystem.service.dto.PageListDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class ActivityController {

    @Autowired
    private ActivityService activityService;
    private static final Logger logger = LoggerFactory.getLogger(ActivityController.class);

    /**
     * 创建活动
     * @param param
     * @return
     */
    @RequestMapping("/activity/create")
    public CommonResult<CreateActivityResult> createActivity(
            @RequestBody @Validated CreateActivityParam param) {
        logger.info("createActivity createActivityParam:{}"
                , JacksonUtils.writeValueString(param));
        CreateActivityDTO activityDTO = activityService.createActivtiy(param);
        return CommonResult.success(convertToCreateActivityResult(activityDTO));
    }

    /**
     * 查找活动列表
     * @param param
     * @return
     */
    @RequestMapping("/activity/find-list")
    public CommonResult<FindActivityListResult> findActivtyList(PageListParam param){
        logger.info("findActivtyList param:{} ",JacksonUtils.writeValueString(param));
        PageListDTO<ActivityDTO> findActivityListDTO =  activityService.findActivityList(param);
        return CommonResult.success(convertToFindActivityListResult(findActivityListDTO));

    }

    /**
     * 根据活动Id获取活动详细信息
     * @param activityId
     * @return
     */
    @RequestMapping("/activity-detail/find")
    public CommonResult<GetActivityDetailResult> getActivityDetail(Long activityId) {
        logger.info("getActivityDetail activityId={}",activityId);
        ActivityDetailDTO detailDTO = activityService.getActivityDetail(activityId);
        return CommonResult.success(convertToGetActivityDetailResult(detailDTO));

    }

    private GetActivityDetailResult convertToGetActivityDetailResult(ActivityDetailDTO detailDTO) {
        if(null == detailDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.GET_ACTIVITY_DETAIL_ERROR);
        }
        GetActivityDetailResult result = new GetActivityDetailResult();
        result.setActivityId(detailDTO.getActivityId());
        result.setActivityName(detailDTO.getActivityName());
        result.setDescription(detailDTO.getDescription());
        result.setValid(detailDTO.valid());

        result.setPrizes(
                detailDTO.getPrizeDoList()
                        .stream()
                        .sorted(Comparator.comparingInt(prizeDTO-> prizeDTO.getPrizeTiers().getCode()))
                        .map(prizeDTO -> {
                            GetActivityDetailResult.Prize prize = new GetActivityDetailResult.Prize();
                            prize.setPrizeId(prizeDTO.getId());
                            prize.setName(prizeDTO.getName());
                            prize.setPrice(prizeDTO.getPrice());
                            prize.setImageUrl(prizeDTO.getImageUrl());
                            prize.setDescription(prizeDTO.getDescription());
                            prize.setPrizeAmount(prizeDTO.getPrizeAmount());
                            prize.setPrizeTierName(prizeDTO.getPrizeTiers().name());
                            prize.setValid(prizeDTO.valid());
                            return  prize;
                        }).collect(Collectors.toList())

        );
        result.setUsers(
                detailDTO.getUserDTOList()
                        .stream()
                        .map(userDTO -> {
                            GetActivityDetailResult.User user = new GetActivityDetailResult.User();
                            user.setUserId(userDTO.getUserId());
                            user.setUserName(userDTO.getUserName());
                            user.setValid(userDTO.valid());
                            return user;
                        }).collect(Collectors.toList())
        );

        return result;
    }

    private FindActivityListResult convertToFindActivityListResult(PageListDTO<ActivityDTO> findActivityListDTO) {
        if(null == findActivityListDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.FIND_ACTIVITY_LIST_ERROR);
        }
        FindActivityListResult result = new FindActivityListResult();
        result.setTotal(findActivityListDTO.getTotal());
        result.setRecords(findActivityListDTO.getRecords()
                .stream()
                .map(activityDTO -> {
                    FindActivityListResult.ActivityInfo activityInfo = new FindActivityListResult.ActivityInfo();
                    activityInfo.setActivityId(activityDTO.getActivityId());
                    activityInfo.setActivityName(activityDTO.getActivityName());
                    activityInfo.setDescription(activityDTO.getDescription());
                    activityInfo.setVaild(activityDTO.valid());
                    return activityInfo;
                }).collect(Collectors.toList())
        );
        return result;
    }

    private CreateActivityResult convertToCreateActivityResult(CreateActivityDTO createActivityDTO) {
        if(null == createActivityDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.CREATE_ACTIVITY_ERROR);
        }
        CreateActivityResult result = new CreateActivityResult();
        result.setActivityId(createActivityDTO.getActivityId());
        return result;
    }

}
